package com.dpiinc.TechPage.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import com.dpiinc.TechPage.BaseActivity
import com.dpiinc.TechPage.R
import com.dpiinc.TechPage.room.RoomAiWriterDatabase
import com.dpiinc.TechPage.room.bean.LabelEntity
import com.dpiinc.TechPage.room.dao.LabelDao
import com.dpiinc.TechPage.user.logic.NoteLabelLogic
import com.dpiinc.TechPage.user.utils.ToastUtils
import com.dpiinc.TechPage.widget.LabelsView
import kotlinx.android.synthetic.main.activity_input_title.*
import kotlinx.android.synthetic.main.activity_input_title.btn_clear
import kotlinx.android.synthetic.main.activity_input_title.toolbar
import java.io.Serializable
import java.util.*

/**
 * 输入标题和选择标签
 * Created by X on 2018/7/6.
 */
class InputTitleActivity : BaseActivity() {

    companion object {
        const val ARG_RESULT_DATA = "arg_result_data"
        const val MAX_SELECTED_LABEL_COUNT = 3
    }

    var labelDao: LabelDao? = null
    private lateinit var curData: ResultData

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_input_title)
        setSupportActionBar(toolbar)
        labelDao = RoomAiWriterDatabase.getInstance(this).labelDao()
        supportActionBar?.setDisplayShowTitleEnabled(false)
        toolbar.setNavigationOnClickListener {
            setResult(Activity.RESULT_CANCELED)
            closeInput()
            finish()
        }
        initView()
        bindView()
        KeyBoard(edt_note_name, true)
    }

    private fun initView() {
        btn_clear.setOnClickListener {
            edt_note_name.setText("")
        }
        edt_note_name.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (s.isNullOrEmpty()) {
                    btn_clear.visibility = View.GONE
                } else {
                    btn_clear.visibility = View.VISIBLE
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        })
    }

    private fun bindView() {
        val labels = RoomAiWriterDatabase.getInstance(this).labelDao().getLabels()
        labels_view.setLabels(true, labels) { _, _, label ->
            //根据data和position返回label需要显示的数据。
            label.content
        }
        labels_view.showAddNew(labels.size < 10)
        labels_view.setOnLabelClickListener { _, _, _, offLimit ->
            if (labels_view.selectLabels.size >= MAX_SELECTED_LABEL_COUNT && offLimit) {
                ToastUtils.showCenterTip(this@InputTitleActivity, getString(R.string.select_label_count_limit_tip))
            }
        }

        labels_view.setGetEtLabelListener(object : LabelsView.OnGetEtLabelListener {
            override fun getEtText(content: String) {
                if (TextUtils.isEmpty(content)) {
                    ToastUtils.showCenterTip(this@InputTitleActivity, getString(R.string.input_title_tag))
                    return
                }

                for (i in 0 until labels.size) {
                    if (labels.get(i).content.equals(content)) {
                        ToastUtils.showCenterTip(this@InputTitleActivity, getString(R.string.label_name_exist))
                        return
                    }
                }

                if (labels.size > 9) {
                    ToastUtils.showCenterTip(this@InputTitleActivity, getString(R.string.toast_max_label_count_limit))
                    return
                }

                NoteLabelLogic.noteLabelEdit(
                        this@InputTitleActivity,
                        NoteLabelLogic.EDITTYPE_ADD,
                        null,
                        content
                ) {
                    val label = LabelEntity(it.getLabelId(), content);
                    labelDao!!.insert(label)
                    ToastUtils.showCenterTip(this@InputTitleActivity, getString(R.string.add_label_success));
                    bindView()
                }

            }

        })


        val extra = intent.getSerializableExtra(ARG_RESULT_DATA)
        extra?.let {
            curData = it as ResultData
            if (edt_note_name.text!!.isEmpty())
                edt_note_name.setText(curData.noteName)
            edt_note_name.setSelection(curData.noteName?.length ?: 0)
            curData.labels?.let {
                val selectedLabelPositions = getSelectLabelPositions(labels, it)
                labels_view.setSelects(selectedLabelPositions)
            }
        }
    }

    private fun getSelectLabelPositions(allLabels: List<LabelEntity>, selectedLabels: List<LabelEntity>): ArrayList<Int> {
        val positions = ArrayList<Int>()
        for (i in allLabels.indices) {
            selectedLabels.forEach { selectedLabel ->
                if (allLabels[i].id == selectedLabel.id) {
                    positions.add(i)
                }
            }
        }
        return positions
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_select_label, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_save -> {
                if (checkIfModified()) {
                    val data = Intent()
                    val noteName = edt_note_name.text.toString()
                    val result = ResultData(noteName, labels_view.getSelectLabelDatas())
                    data.putExtra(ARG_RESULT_DATA, result)
                    setResult(Activity.RESULT_OK, data)
                } else {
                    setResult(Activity.RESULT_CANCELED)
                }
                closeInput()
                finish()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        setResult(Activity.RESULT_CANCELED)
        closeInput()
        finish()
    }

    fun closeInput() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (imm.isActive) {
//            val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
//            inputMethodManager.hideSoftInputFromWindow(this.currentFocus!!.windowToken, 0)
            imm.hideSoftInputFromWindow(edt_note_name.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    data class ResultData(val noteName: String?, val labels: List<LabelEntity>?) : Serializable

    private fun checkIfModified(): Boolean {
        val newNoteName = edt_note_name.text.toString()
        val newLabels: List<LabelEntity> = labels_view.getSelectLabelDatas()
        val curNoteName = curData.noteName ?: ""
        if (newNoteName != curNoteName) {
            return true
        }
        val curLabelSize = curData.labels?.size ?: 0
        if (newLabels.size != curLabelSize) {
            return true
        }
        curData.labels?.forEach { curLabel ->
            var equals = false
            for (newLabel in newLabels) {
                if (curLabel.id == newLabel.id) {
                    equals = true
                    break
                }
            }
            if (!equals) {
                return true
            }
        }
        return false
    }

    //强制显示或者关闭系统键盘
    fun KeyBoard(txtSearchKey: EditText, status: Boolean) {
        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                val m = txtSearchKey.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                if (status) {
                    m.showSoftInput(txtSearchKey, InputMethodManager.SHOW_FORCED)
                } else {
                    m.hideSoftInputFromWindow(txtSearchKey.windowToken, 0)
                }
            }
        }, 300)
    }
}
